package lu.med.praxiswahl.wahlumed.client.laborbuch;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;

import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
import javax.swing.text.JTextComponent;

import lu.med.praxiswahl.wahlumed.client.utilities.KillInterface;
import lu.med.praxiswahl.wahlumed.client.wclient.Main;

public class LaborbuchCellEditor extends AbstractCellEditor implements
		TableCellEditor, KillInterface, ActionListener {

	/**
     * 
     */
	private static final long serialVersionUID = 995596214932481243L;
	private Component component;
	private LaborbuchDataModel model;
	private String val = "";
	private Main dataManager;
	private int valASInteger = 0;

	public LaborbuchCellEditor(LaborbuchDataModel model, Main dataManager) {
		this.model = model;
		this.dataManager = dataManager;
		// model.setKiller(this);
	}

	public void actionPerformed(ActionEvent e) {
	}

	public Object getCellEditorValue() {
		if (component.getClass() == JButton.class) {
			// Gibt Dummy Wert zurück
			return "";
		} else if (component.getClass() == JTextField.class) {
			JTextField jtf = (JTextField) component;
			return jtf.getText();
		}
		return "";
	}

	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, final int row, final int column) {
		/*
		 * val = (String) model.getValueAt(row, column); JTextField jtf = new
		 * JTextField(); jtf.setText(val); if (column == 1) { // Datumsspalte
		 * jtf.setText(model.getOriginalDate(row)); } //jtf.selectAll(); component
		 * = jtf;
		 */

		if (column == 0) {
			this.valASInteger = (Integer) model.getValueAt(row, column);

			JTextField jtf = new JTextField();
			jtf.setText("" + valASInteger);
			jtf.setBackground(Color.WHITE);
			jtf.setBorder(BorderFactory.createLineBorder(Color.GREEN));

			//jtf.selectAll();
			component = jtf;

			component.addFocusListener(new java.awt.event.FocusListener() {

				@Override
				public void focusGained(FocusEvent e) {
					lockRowEntry(row);

				}

				@Override
				public void focusLost(FocusEvent e) {
					JTextComponent cell = (JTextComponent) e.getSource();
					Object data = cell.getText();
					model.setValueAt(data, row, column);
				}
			});

			return component;

		} else {
			val = (String) model.getValueAt(row, column);
			JTextField jtf = new JTextField();
			jtf.setText(val);
			if (column == 1) {
				// Datumsspalte
				jtf.setText(model.getOriginalDate(row));
			}
			jtf.setBackground(Color.WHITE);
			jtf.setBorder(BorderFactory.createLineBorder(Color.GREEN));

			//jtf.selectAll();
			component = jtf;

			component.addFocusListener(new java.awt.event.FocusListener() {

				@Override
				public void focusGained(FocusEvent e) {
					lockRowEntry(row);

				}

				@Override
				public void focusLost(FocusEvent e) {
					JTextComponent cell = (JTextComponent) e.getSource();
					Object data = cell.getText();
					model.setValueAt(data, row, column);
				}
			});

			return component;

		}
	}

	public void lockRowEntry(int rowEntry) {
		if (isLocked(rowEntry)) {

			String locker = ""
					+ model.getData().get(rowEntry).getLastEditor().getLogin();
			JLabel lockingMessage = new JLabel(
					"Diese Zeile wird gerade von User [" + locker
							+ "] bearbeitet!");
			lockingMessage.setIcon(new javax.swing.ImageIcon(getClass()
					.getResource("/lock.png")));
			lockingMessage.setForeground(new java.awt.Color(255, 0, 0));
			lockingMessage.setFont(new Font("Verdana", Font.PLAIN, 11));
			JOptionPane.showMessageDialog(null, lockingMessage);
			this.cancelCellEditing();
			model.refresh();
			return;
		} else {
			// Prevents for further Use by others by locking the row
			model.getData().get(rowEntry).setLocked(true);

			// Set the last editor
			model.getData().get(rowEntry).setLastEditor(Main.loggedUser);

			model.getData().get(rowEntry).setChanged(true);

			Thread process = new Thread(new TransferToDatabaseDelegate(model));
			process.start();

			try {
				// Wartet bis den Thread zu ende gegangen ist.
				process.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * checks whether the given row entry is already locked by someone else
	 * 
	 * @param rowEntry
	 */
	public boolean isLocked(int rowEntry) {

		model.lockingRefresh();
		if (model.getData().get(rowEntry).isLocked()) {
			if (model.getData().get(rowEntry).getLastEditor() != null) {

				String lastLocker = model.getData().get(rowEntry)
						.getLastEditor().getLogin();
				if (lastLocker != null && !lastLocker.equals("")
						&& lastLocker != "") {
					if (lastLocker.equals(Main.loggedUser.getLogin())) {
						return false;
					} else {
						return true;
					}
				} else {
					return false;
				}
			} else {
				return false;
			}

		} else {
			return false;
		}
	}

	public void killEditing() {
		this.cancelCellEditing();
	}
}